<?php
class Balance_model extends MY_Model
{
	public $table = 'balances';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function get_by($fund_id, $agency_id, $year, $month, $is_prev = FALSE)
	{
		$year -= 543;
		if($is_prev)
		{
			if($month == 1)
			{
				$year -= 1;
				$month = 12;
			}
			else
			{
				$month -= 1;
			}
		}
		$sql = "SELECT T.ID, BD.PRICE
		FROM REGISTER_TITLES AS T
		LEFT JOIN ( 
			SELECT D.TITLE_ID, D.PRICE 
			FROM BALANCES AS B
			JOIN BALANCE_DETAILS AS D ON D.BALANCE_ID = B.ID
			WHERE FUND_ID = $fund_id
			AND AGENCY_ID = $agency_id 
			AND YEAR_RECORD = $year
			AND MONTH_RECORD = $month
		) AS BD ON BD.TITLE_ID = T.ID
		WHERE T.ID IN (8,9,10,11,12,13,14,15,16,17,18,19,20,21)
		";
		return $this->db->getassoc($sql);
	}
	
	public function update_by($fund_id, $agency_id, $year, $month)
	{
		
	}
	
	public function delete_by($fund_id, $agency_id, $year, $month)
	{
		$year -= 543;
		$sql = "SELECT ID 
		FROM BALANCES 
		WHERE FUND_ID = $fund_id
		AND AGENCY_ID = $agency_id 
		AND  YEAR_RECORD = $year AND MONTH_RECORD = $month";
		$id = $this->db->getone($sql);
		if($id)
		{
			$this->db->execute('DELETE BALANCES WHERE ID = ?', $id);
			$this->db->execute('DELETE BALANCE_DETAILS WHERE BALANCE_ID = ?', $id);	
		}
	}
}
?>